import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import { CacheService } from '@app/cache';
import { AlicloudService } from '@app/alicloud';
import { DeviceService } from '../device/device.service';
import { DEVICE_CTR_ORDER } from 'constant/DEVICE_CTR_ORDER';

@Injectable()
export class TestService {

    constructor(
        private readonly db:DbService,
        private readonly cache:CacheService,
        private readonly alicloud:AlicloudService,
        private readonly deivce:DeviceService,
    ){
        
    }

    async test(deviceId:number, userId:number) {
        const key = 'test.' + deviceId
        const had = await this.cache.get(key)
        if(had != null) return null


        let lockKey = 'test.lock.' + deviceId
        const lock = await this.cache.set(lockKey, '', 10, 'NX')
        if(!lock) return null
        const device = await this.db.device.findOne({id : deviceId}, {userId : true, deviceTypeId : true, aliSecret : true})
        
        if(!device || device.userId != userId) return null

        const deviceType = await this.db.deviceType.findOne({id : device.deviceTypeId}, {aliProduct : true})
        if(!deviceType) return null

        const r = await this.db.waterTest.insert({
            userId,
            deviceId,
            createTime : Math.floor(Date.now() / 1000),
            //data : []
        })

        if(r != null && r.affectedRows > 0) {
            this.cache.set(key, r.rows[0].id)
            this.deivce.pub(deviceId, deviceType.aliProduct, {
                v : "ss_1",
                goal: "0",
                cmd : DEVICE_CTR_ORDER.SET_CHECK_STEP,
                param : "1",
                port : '0',
                childPort: "",
                msgId : String(r.rows[0].id)
            })
        }
        
    }

}
